var madeChanges = false;
function showSchedule()
{
    console.log('showSchedule(): Entering');
	var url = urlSignupBase+'/slots/list_slots?school_id='+schoolID;
    if (curView == 'TEACHER') {
        url+='&family_id=&teacher_id='+encodeURIComponent(userID);
    } else {
        url+='&teacher_id=&family_id='+encodeURIComponent($("#family_id").val());
    }
    console.log(url);
    var dbg = '';
    //dbg = "url="+url);
    $("#helpscreen").html("<i>Loading content...</i>"+dbg).dialog({ title: 'Creating List' }).dialog("open");
    jQuery.ajax({url: url, dataType: "json"})
    .done(function( json ) {
        if (json.error) {
            alert(json.error);
        } else if (json.success) {
            console.log(json);
            console.log(json.success);
            console.log(json.error);
            //console.log(json.list);
            $("#helpscreen").dialog("close");
            $("#schedule-div").html(json.html).dialog('open');
        }
    });
}
function familyChanged()
{
    if (typeof familyChanged.family_id == 'undefined' || familyChanged.family_id != $("#family_id").val()) {
        familyChanged.family_id = $("#family_id").val();
        redrawTable();
    }
    return true;
}
// Note that any change here needs to be reflected in the initial draw of the table in PHP
function redrawTable()
{
    var familyID = $("#family_id").val();
    var family_name = $("#family_id option:selected").text();
    console.log("redrawTable(): Entering familyID="+familyID+" name="+family_name);
    for (var i=0; i<slots.length; i++) {
        //console.log("redrawTable(): i="+i+", name="+slots[i].family_name+", id="+slots[i].id);
        changeSlot(i);
    }
}
// Note that any change here needs to be reflected in the initial draw of the table in PHP
function unsignupButtonText(id, name)
{
    return "<button class='ui-state-highlight' onclick='unsignup("+id+")'>"+name+"</button>";
}
// Note that any change here needs to be reflected in the initial draw of the table in PHP
function signupButtonText(id)
{
    return "<button onclick='signup("+id+")'>Sign&nbsp;Up</button>";
}
function unsignup(slot_id)
{
    var familyID = $("#family_id").val();
    if (!familyID) {
        alert('You must choose your name first');
        $("#family_id").focus();
        return;
    }
    if (confirm('Press OK to unregister yourself for this timeslot.')) {
        changeFamily(slot_id, '!NULL!');
    }
}
function signup(slot_id)
{
    //var family_id = $("#family_id").html();
    //var family_id = <?= $familyID ?>;
    //if (!family_id) {
        //alert('You must enter your name first');
        //$("#client_name").focus();
        //return;
    //}
    var familyID = $("#family_id").val();
    changeFamily(slot_id, familyID);
}
function changeFamily(slot_id, family_id)
{
    console.log(slot_id);
    madeChanges = true;
    // <?php echo "var school_id = $schoolID;\n"; ?>
    var familyID = $("#family_id").val();
    // console.log(urlSignupBase);
    var url = urlSignupBase+"/slots/ajax_update"+"?slot_id="+encodeURIComponent(slot_id)+"&family_id="+encodeURIComponent(family_id)+"&school_id="+encodeURIComponent(schoolID);
    console.log(url);
    jQuery.ajax({url: url, dataType: "json"})
        .done(function(json) {
            console.log("slots/ajax_update - done!");
            console.log(json);
            //console.log("slotid="+slot_id);
            //console.log("family_id="+json.family_id);
            if (json.success) {
                if (json.conflicts > 0) {
                    var msg = 'NOTE: You are already signed up elsewhere during that time! ('+json.conflicts+' time';
                    if (json.conflicts > 1)
                        msg += 's';
                    msg += ' in addition to this slot)';
                    alert(msg);
                }
                if (json.family_id == '!NULL!') {
                    json.family_id = null;
                    json.family_name = null;
                }
                changeSlot(-1, json.id, json.family_id, json.name);
            } else {
                //console.log('error');
                console.log(json);
                console.log(json.error);
                alert(json.error);
            }
        });
}
// If idx is negative then we find the appropriate idx in slots
// If idx is non-neg then other args are optional because we can get them from slots
function changeSlot(idx, slot_id, family_id, family_name)
{
    var familyID = $("#family_id").val();
    console.log('changeSlot('+idx+','+slot_id+','+family_id+','+family_name+'): familyID='+familyID);
    if (idx < 0) {
        var found = false;
        for (i = 0; i < slots.length; i++) {
            if (slots[i].id == slot_id) {
                found = true;
                idx = i;
                break;
            }
        }
        if (!found) { return false; }
        console.log('changeSlot(): found: idx='+idx);
    }
    if (typeof slot_id == 'undefined') { slot_id = slots[idx].id; }
    if (typeof family_id == 'undefined') { 
        family_id = slots[idx].family_id;
        family_name = slots[idx].family_name; 
    } else if (family_id != slots[idx].family_id) { 
        slots[idx].family_id = family_id; 
        slots[idx].family_name = family_name; 
    }
    console.log('changeSlot(): slot_id='+slot_id+', family_id='+family_id+', family_name='+family_name);

    if (slots[idx].family_id) {
        console.log('changeSlot(): has slots['+idx+'].family_id='+slots[idx].family_id);
        if (slots[idx].family_id == familyID) {
            html = unsignupButtonText(slots[idx].id, family_name);
        } else {
            html = slots[idx].family_name;
        }
    } else {
        console.log('changeSlot(): no slots['+idx+'].family_id');
        html = signupButtonText(slots[idx].id);
    }
    //console.log("changeSlot(): html="+html);
    $("#detail_"+slots[idx].id).html(html);
}
// This function provides a little optimization in case someone leaves the page open
// for a long time - it will check less and less often, lowering load on the server
//   (comments assume this function is being called on an interval of 15 seconds)
function timedCheckForChanges(seconds)
{
    arguments.callee.count = ++arguments.callee.count || 1;
    if (madeChanges) {
        arguments.callee.count = 1;
        madeChanges = false;
    }

    var time = new Date();
    //console.log( ("0" + time.getHours()).slice(-2)   + ":" + ("0" + time.getMinutes()).slice(-2) + ":" + ("0" + time.getSeconds()).slice(-2)+ ' - timedCheckForChanges(): Entering');
    if (arguments.callee.count > 720) { // after 3 hours
        if (arguments.callee.count % 120 != 0) // check only every 30 mins
            return;
    } else if (arguments.callee.count > 480) { // after 2 hrs
        if (arguments.callee.count % 60 != 0) // check only every 15 mins
            return;
    } else if (arguments.callee.count > 240) { // after 60 mins
        if (arguments.callee.count % 20 != 0) // check only every 5 mins
            return;
    } else if (arguments.callee.count > 40) { // after 10 mins
        if (arguments.callee.count % 4 != 0) // check only every 1 mins
            return;
    }
    checkForChanges(seconds);
}
function checkForChanges(seconds)
{
    //console.log("checkForChanges(): Entering");
    //<?php echo "var school_id = $schoolID;\n"; ?>
    var url = urlSignupBase+"/slots/ajax_check4changes?school_id="+encodeURIComponent(schoolID)+"&dept_id="+encodeURIComponent(deptID)+"&seconds="+encodeURIComponent(seconds);
    console.log(url);
    jQuery.ajax({url: url, dataType: "json"})
        .done(function(json) {
            console.log(json);
            console.log("check4changes(): success="+json.success);
            //console.log(json);
            for (var row in json.changes) {
                //console.log('row:');
                //console.log(row);
                if (json.changes[row].id) {
                    //console.log("check4changes(): id="+json.changes[row].id+", name="+json.changes[row].family_name);
                    var found=false;
                    var changes=0;
                    for (var i=0; i<slots.length && !found; i++) {
                        if (json.changes[row].id == slots[i].id) {
                            found=true; // don't loop anymore - small optimization
                            var newid=(json.changes[row].family_id == null)?'':json.changes[row].family_id;
                            if (newid != slots[i].family_id) {
                                //console.log("check4changes(): id="+json.changes[row].id+", old name="+slots[i].family_name);
                                slots[i].family_name=(json.changes[row].family_name == 'null')?'':json.changes[row].family_name;
                                slots[i].family_id=(json.changes[row].family_id == 'null')?'0':json.changes[row].family_id;
                                //console.log("check4changes(): id="+json.changes[row].id+", new name="+slots[i].family_name);
                                changes++;
                            }
                        }
                    }
                }
            }
            if (changes > 0)
                redrawTable();
        });
}
$(document).ready(function () {
//    $("#client_name").autocomplete({
//        source: "ajax_client.php",
//        change: function (event, ui) { clientChanged(); },
//        focus: function (event, ui) { 
//            //console.log(ui);
//            $("#client_name").val(ui.item.value); 
//            clientChanged(); 
//        },
//    });
    // check for changes within last 20 seconds every 15 seconds
    setInterval(function () {timedCheckForChanges(20);}, 15000);
    $( "#schedule-div" ).dialog({ 
         autoOpen: false
        ,modal: true
        ,width: 'auto'
        ,maxHeight: $(document).height() * 0.8
        ,maxWidth: $(document).width() * 0.8
        ,buttons: {
            Cancel: {
                text: "Cancel",
                click: function() {
                    $(this).dialog("close");
                }
            },
            Print: {
                text: "Print",
                click: function() {
                    $(this).printArea({mode: 'popup', popClose: 1, });
                }
            },
        }
    });
    //alert("Wow! I got here!");
    //$(".link2button").button().css({width: '200px'});
});

